package jp.gr.jted.util;

import jp.gr.jted.R;
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

/**
 * The Class Util.
 */
public class Util {

	/**
	 * Instantiates a new util.
	 */
	private Util() {
	}

	/**
	 * Checks if is first launch.
	 *
	 * @param activity the activity
	 * @return true, if is first launch
	 * @throws NameNotFoundException the name not found exception
	 */
	public static synchronized boolean isFirstLaunch(Activity activity) throws NameNotFoundException {
		boolean flag = false;
		// バージョン名を取得
		PackageManager packageManager = activity.getPackageManager();
		SharedPreferences sp = activity.getPreferences(Activity.MODE_PRIVATE);
		PackageInfo packageInfo =
			packageManager.getPackageInfo(activity.getPackageName(),
					PackageManager.GET_ACTIVITIES);
		String versionName = packageInfo.versionName;
		String sharedVersionName = sp.getString(activity.getString(R.string.app_name), "");
		if (!versionName.equals(sharedVersionName)) {
			flag = true;
		}
		return flag;
	}

	/**
	 * Write version to device.
	 *
	 * @param activity the activity
	 * @throws NameNotFoundException the name not found exception
	 */
	public static synchronized void writeVersionToDevice(Activity activity) throws NameNotFoundException {
		SharedPreferences sp = activity.getPreferences(Activity.MODE_PRIVATE);
		PackageManager packageManager = activity.getPackageManager();
		PackageInfo packageInfo =
			packageManager.getPackageInfo(activity.getPackageName(),
					PackageManager.GET_ACTIVITIES);
		String versionName = packageInfo.versionName;
		Editor editor = sp.edit();
		editor.putString(activity.getString(R.string.app_name), versionName);
		editor.commit();
	}

	// ネットワーク接続チェック
	/**
	 * Can network communication.
	 *
	 * @param activity the activity
	 * @return true, if successful
	 */
	public static synchronized boolean canNetworkCommunication(Activity activity) {
		boolean flag = false;
		ConnectivityManager cm;
		cm = ((ConnectivityManager) activity.getSystemService(Activity.CONNECTIVITY_SERVICE));
		NetworkInfo networkInfo = cm.getActiveNetworkInfo();
		if (networkInfo != null) {
			if (networkInfo.isConnected()) {
				flag = true;
			}
		}
		return flag;
	}
}
